//package com.example.springbootlearn.netty.okhttp;
//
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.java_websocket.client.WebSocketClient;
//import org.java_websocket.handshake.ServerHandshake;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Service;
//
//import java.net.URI;
//import java.net.URISyntaxException;
//import java.util.Iterator;
//import java.util.Map;
//import java.util.concurrent.ConcurrentHashMap;
//import java.util.concurrent.TimeUnit;
//import java.util.concurrent.atomic.AtomicBoolean;
//
///**
// * @Author libo
// * @Date 2024/4/12 15:57
// */
//
//@Slf4j
//@Service
//@RequiredArgsConstructor
//public class JavaAsrWebsocket {
//
//    private static final Object ERROR_OBJECT = new Object();
//    private static final Map<String, WebSocketClient> WEB_SOCKET_MAP = new ConcurrentHashMap<>();
//    //    public static com.github.benmanes.caffeine.cache.Cache<String, AtomicBoolean> WEB_SOCKET_LOGGED_MAP = Caffeine.newBuilder()
////            .removalListener(((key, value, cause) -> {
////                log.info("AsrWebsocket淘汰通知,key: {} 原因: {} value: {}", key, cause, value);
////            }))
////            .maximumSize(10000)
////            .expireAfterAccess(2, TimeUnit.HOURS)
////            .build();
//    private static boolean PRINT_ED = false;
//    private final Map<WebSocketClient, Object> errorWebSockets = new ConcurrentHashMap<>();
//    // 使用 ConcurrentHashMap 存储每个 WebSocket 对应的日志输出状态
//    Map<String, AtomicBoolean> WEB_SOCKET_LOGGED_MAP = new ConcurrentHashMap();
//    @Value("${yuyitech.asrserver.url:ws://10.207.131.20:5060}")
//    private String txAsrWsUrl;
//    @Value("${yuyitech.asrserver.vadTime:500}")
//    private String vadTime;
//
//    public void initAsrWsClient(String sessionId) {
//        try {
//            String left = getFinalSessionId(sessionId, 0);
//            String right = getFinalSessionId(sessionId, 1);
//            create(left);
//            create(right);
//        } catch (Exception e) {
//            closeAsrWsClient(sessionId);
//            log.error("创建asr连接出错", e);
//        }
//    }
//
//    public void create(String sessionId) throws InterruptedException, URISyntaxException {
//
//        StringBuilder urlStr = new StringBuilder(txAsrWsUrl);
////                .append("/realtime_asr_ws_private?")
////                .append("&voice_format=1")
////                .append("&needvad=1")
////                .append("&vad_silence_time=").append(vadTime)
////                .append("&voice_id=").append(sessionId);
//        log.info("java-WS ASR_MMMM voice_id ===>{} create ws url===>{}", sessionId, urlStr);
//        URI uri = new URI(urlStr.toString());
//        WebSocketClient webSocketClient = new WebSocketClient(uri) {
//            @Override
//            public void onOpen(ServerHandshake serverHandshake) {
//                log.info("java-WS ASR_MMMM voice_id ==={} 连接成功", sessionId);
////                addOnlineAsrCount();
//            }
//
//            @Override
//            public void onMessage(String text) {
//                log.info("voice_id ===>{} success:{}", sessionId, text);
//            }
//
//            @Override
//            public void onClose(int code, String reason, boolean remote) {
//                log.info("voice_id ==={} 连接关闭, 代码={}, 原因={}", sessionId, code, reason);
//                errorWebSockets.compute(this, (ws, obj) -> {
//                    if (obj != null) {
//                        log.info("voice_id ===>{} websocket触发了onFailure方法还是会调用onClosed", sessionId);
//                    } else {
////                        reduceOnlineAsrCount();
//                    }
//                    return null;
//                });
//            }
//
//            @Override
//            public void onError(Exception ex) {
//                log.error("voice_id ==={} 发生错误", sessionId, ex);
//                if (errorWebSockets.putIfAbsent(this, ERROR_OBJECT) == null) {
////                    reduceOnlineAsrCount();
//                    // 统计错误的次数
////                    addFailAsrCount();
//                    this.close();
//                } else {
//                    log.info("voice_id ===>{} 同一个websocket会多次触发方法", sessionId);
//                }
//            }
//        };
//        // 最多等5s
//        webSocketClient.connectBlocking(5, TimeUnit.SECONDS);
//        WEB_SOCKET_MAP.put(sessionId, webSocketClient);
//        WEB_SOCKET_LOGGED_MAP.put(sessionId, new AtomicBoolean(false));
//    }
//
////    private void handleAsrRes(MsgResp msgResp) {
////        try {
////            FlowHandleService handleService = SpringUtil.getBean(FlowHandleService.class);
////            handleService.handle(msgResp);
////        } catch (Exception e) {
////            log.error("处理转义失败 转义内容为{}", msgResp, e);
////        }
////    }
//
//    public void sendData(String sessionId, int role, String data) {
//        String realSessionId = getFinalSessionId(sessionId, role);
//        WebSocketClient webSocketClient = WEB_SOCKET_MAP.get(realSessionId);
//
//        if (webSocketClient == null || !webSocketClient.isOpen()) {
//            // todo 暂时考虑单机情况
//            // 获取当前 WebSocket 对应的日志输出状态,如果不存在则创建
//            AtomicBoolean atomicBoolean = WEB_SOCKET_LOGGED_MAP.get(realSessionId);
//            if (atomicBoolean.compareAndSet(false, true)) {
////                long realTimeAsrCount = resourceStatisticsService.getRealTimeAsrCount();
//                log.error("找不到连接sessionId = {} 此时的ASR连接数为个", realSessionId);
//            }
//            return;
//        }
//        webSocketClient.send(data);
//    }
//
//    public void closeAsrWsClient(String sessionId) {
//        String left = getFinalSessionId(sessionId, 0);
//        String right = getFinalSessionId(sessionId, 1);
//        destroy(left);
//        destroy(right);
//    }
//
//    public void destroy(String sessionId) {
//        WebSocketClient webSocketClient = WEB_SOCKET_MAP.remove(sessionId);
//        if (webSocketClient != null) {
//            webSocketClient.close();
//        }
//    }
//
//    private String getFinalSessionId(String sessionId, int role) {
//        return sessionId + "_" + role;
//    }
//
//    public void closeByPhone(String caller) {
//        Iterator<Map.Entry<String, WebSocketClient>> iterator = WEB_SOCKET_MAP.entrySet().iterator();
//        while (iterator.hasNext()) {
//            Map.Entry<String, WebSocketClient> entry = iterator.next();
//            String sessionId = entry.getKey();
//            if (sessionId != null && sessionId.startsWith(caller)) {
//                iterator.remove();
//                WebSocketClient webSocketClient = entry.getValue();
//                webSocketClient.close();
//            }
//        }
//    }
//
//
//}
